package com.project.vocabulary.service;

import com.project.vocabulary.dao.WordMapper;
import com.project.vocabulary.model.Word;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Description:
 *
 * @author : luyao.duan
 * @since : 2019-10-26 19:55:59
 **/
@Service
public class WordService {

    @Autowired
    private WordMapper wordMapper;

    public List<Word> getWordList() {
        return wordMapper.getWordList();
    }

    public Integer getSumWord() {
        return wordMapper.sumWord();
    }

    public Map getResult() {
        Map map = new HashMap();
        List resList = new ArrayList();
        Integer sum = getSumWord();
        List<Word> list = wordMapper.selectByIds(getRands(sum,30));
        for(Word word : list){
            Map tmp = new HashMap();
            tmp.put("rightAns",word);
            tmp.put("wrongAns",get3WrongAns());
            resList.add(tmp);
        }
        map.put("res", resList);
        return map;
    }

    private List<Integer> getRands(Integer range, Integer num) {
        Random ran = new Random();
        SortedSet set = new TreeSet();
        for (int i = 0; i < num; i++) {
            set.add(ran.nextInt(range) + 1);
        }
        while (set.size() < num) {
            set.add(ran.nextInt(range) + 1);
        }
        return new ArrayList<>(set);
    }

    private List<String> get3WrongAns(){
        List<Word> listWrongAns = wordMapper.selectByIds(getRands(getSumWord(),3));
        List<String> ans = new ArrayList<>();
        for(Word word : listWrongAns){
            ans.add(word.getTranslation());
        }
        return ans;
    }
}
